package com.jtech.together.util;

import android.media.MediaRecorder;
import android.os.Handler;
import android.os.Message;

import java.io.File;
import java.io.IOException;

/**
 * 录音方法
 * Created by wuxubaiyang on 2017/5/16.
 */

public class RecordAudio {
    //默认最大时长为一分钟
    private static final int DEFAULT_MAX_LENGTH = 1000 * 60 * 60;

    private OnRecordAudioListener onRecordAudioListener;
    private MediaRecorder mediaRecorder;
    private File audioFile;
    private File filePath;
    private long startTime;
    private int BASE = 3000;
    private int SPACE = 100;// 间隔取样时间

    private final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (null != mediaRecorder) {
                long time = System.currentTimeMillis() - startTime;
                if (time >= DEFAULT_MAX_LENGTH) {
                    //如果大于最大录音限制则自动停止录音
                    stopRecord();
                    return;
                }
                float amplitude = mediaRecorder.getMaxAmplitude() / BASE;
                if (null != onRecordAudioListener) {
                    onRecordAudioListener.onUpdate(amplitude, time);
                }
                handler.sendEmptyMessageDelayed(0, SPACE);
            }
        }
    };

    /**
     * 主构造
     *
     * @param filePath
     */
    public RecordAudio(File filePath) {
        this.filePath = filePath;
    }

    /**
     * 准备工作
     */
    public boolean prepare() {
        return prepare(-1);
    }

    /**
     * 准备工作
     *
     * @param maxLength
     */
    public boolean prepare(int maxLength) {
        //判断目录是否存在，不存在则创建
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            //实例化录音对象
            this.mediaRecorder = new MediaRecorder();
            //设置麦克风
            this.mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            //设置声音采样
            this.mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
            //设置输出格式为amr_nb
            this.mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            //设置输出路径
            audioFile = new File(filePath, System.currentTimeMillis() + ".amr");
            this.mediaRecorder.setOutputFile(audioFile.getAbsolutePath());
            //设置最大录音时长
            this.mediaRecorder.setMaxDuration(maxLength != -1 ? maxLength : DEFAULT_MAX_LENGTH);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            mediaRecorder = null;
            return false;
        }
    }

    /**
     * 设置录音监听
     *
     * @param onRecordAudioListener
     */
    public void setOnRecordAudioListener(OnRecordAudioListener onRecordAudioListener) {
        this.onRecordAudioListener = onRecordAudioListener;
    }

    /**
     * 开始录音
     */
    public void startRecord() {
        if (null == mediaRecorder) {
            if (null != onRecordAudioListener) {
                onRecordAudioListener.onError();
            }
            return;
        }
        try {
            //准备录音
            mediaRecorder.prepare();
            //开始录音
            mediaRecorder.start();
            //记录开始时间
            startTime = System.currentTimeMillis();
            //执行回调
            handler.sendEmptyMessageDelayed(0, SPACE);
            return;
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (null != onRecordAudioListener) {
            onRecordAudioListener.onError();
        }
    }

    /**
     * 停止录音
     *
     * @return
     */
    public void stopRecord() {
        if (null == mediaRecorder) {
            return;
        }
        try {
            mediaRecorder.stop();
            mediaRecorder.reset();
            mediaRecorder.release();
            mediaRecorder = null;
            if (null != onRecordAudioListener) {
                onRecordAudioListener.onStop(audioFile);
            }
            return;
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            if (null != mediaRecorder) {
                mediaRecorder.reset();
                mediaRecorder.release();
                mediaRecorder = null;
            }
        }
        if (null != onRecordAudioListener) {
            onRecordAudioListener.onError();
        }
    }

    /**
     * 取消录音
     */
    public void cancelRecord() {
        if (null == mediaRecorder) {
            return;
        }
        try {
            mediaRecorder.stop();
            mediaRecorder.reset();
            mediaRecorder.release();
            mediaRecorder = null;
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            if (null != mediaRecorder) {
                mediaRecorder.reset();
                mediaRecorder.release();
                mediaRecorder = null;
            }
        }
    }

    /**
     * 录音监听
     */
    public interface OnRecordAudioListener {
        void onUpdate(float amplitude, long time);

        void onStop(File audioFile);

        void onError();
    }
}